import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {

    private ServerSocket serverSocket=null;

    public TcpServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }

    public void start() throws IOException {

        ExecutorService executorService= Executors.newCachedThreadPool();


        while(true){
            Socket socket=serverSocket.accept();

                executorService.submit(()->{

                    processConnection(socket);

                });



        }




    }

    private String process(String request) {

        return request;
    }


    private void processConnection(Socket socket)  {


            System.out.println("客户端上线");

           try(InputStream inputStream=socket.getInputStream();
               OutputStream outputStream=socket.getOutputStream()){

               //套一层壳
               Scanner sc=new Scanner(inputStream);
               PrintWriter writer=new PrintWriter(outputStream);

               while(true) {
                   if (!sc.hasNext()) {
                       System.out.println("客户端下线");
                       break;

                   }


                   //套壳读请求
                   String request = sc.next();
                   //套壳回响
                   String respond = process(request);


                   writer.println(respond);

                   writer.flush();

                   System.out.println("已经回响"+"ip和端口号:"+socket.getInetAddress());
               }

               } catch (IOException e) {
                   throw new RuntimeException(e);
               }finally {
                   try {
                       socket.close();
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }

               }


               }


    public static void main(String[] args) throws IOException {
       TcpServer tcpServer=new TcpServer(9090);
       tcpServer.start();

    }

        }



